package background;

/**
 * 描述：     观察者模式
 * count的值有可能是 0 ,也有可能是100
 */
public class MultiThreadsError5 {

    int count;

    // main方法入口
    public static void main(String[] args) {
        MySource mySource = new MySource();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Event event = new Event() {
                };
                for (int i = 0; i < 3; i++) {
                    try {
                        Thread.sleep(450);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mySource.eventCome(event);
                }
            }
        }).start();

        MultiThreadsError5 multiThreadsError5 = new MultiThreadsError5(mySource);
    }

    //构造函数
    public MultiThreadsError5(MySource source) {
        source.registerListener(new EventListener() {
            @Override
            public void onEvent(Event e) {
                System.out.println("\n我得到的数字是" + count + " 当前线程是:" + Thread.currentThread().getName() + " event的hashCode是" + System.identityHashCode(e));
            }
        });

        for (int i = 0; i < 500; i++) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.print(" 当前线程是" + Thread.currentThread().getName() + " " + i);
        }
        count = 100;
    }


    static class MySource {

        private EventListener listener;

        void registerListener(EventListener eventListener) {
            System.out.println("registerListener方法执行了.当前线程是:" + Thread.currentThread().getName() + " eventListener的hashCode是:" + System.identityHashCode(eventListener));
            this.listener = eventListener;
        }

        void eventCome(Event e) {
            if (listener != null) {
                listener.onEvent(e);
            } else {
                System.out.println("还未初始化完毕呢...");
            }
        }

    }

    interface EventListener {

        void onEvent(Event e);
    }

    interface Event {

    }
}
